package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import com.sky.utils.BloomUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.PostConstruct;
import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private BloomUtil bloomUtil;

    @PostConstruct // 应用启动时自动执行
    public void initActiveUserBloomFilter() {
        // 1. 查询所有活跃用户 ID
        List<String> activeUsernames = employeeMapper.selectAllUserName();
        // 2. 初始化布隆过滤器（假设预期插入量 100000，误判率 0.001）
        bloomUtil.initFilter("active_user", 100000, 0.001);
        // 3. 批量添加数据
        bloomUtil.addAll("active_user", activeUsernames);
        log.info("布隆过滤器初始化完成:{}", activeUsernames);
    }

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        // 1. 先查布隆过滤器（快速判断是否存在）
        if (!bloomUtil.mightContain("active_user", username)) {
            log.info("用户不存在或非活跃: {}", username);
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        // 2. 布隆过滤器认为可能存在，继续查库验证
        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        //将前端提供的明文密码改为md5格式
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    /**
     * 增加员工
     * @param employeeDTO
     */
    @Override
    public void save(EmployeeDTO employeeDTO) {
        //当两个类的属性名相同时可以通过Bean来将一个类中的属性赋值给另一个类中对应的属性名相同的属性
        //对象属性拷贝
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO, employee);

        //设置状态，默认状态正常，1为正常，0为异常
        //为了方便修改和规范，特意设置了常量类，用常量类来为常量属性赋值
        employee.setStatus(StatusConstant.ENABLE);

        //设置密码，默认123456
        //注意要设置成md5编码，同理需要使用常量类
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));

        //设置创建时间和修改时间，使用当前时间
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());

        //设置创建者的用户id
        employee.setCreateUser(BaseContext.getCurrentId());
        employee.setUpdateUser(BaseContext.getCurrentId());

        //调用mapper
        employeeMapper.insert(employee);
    }

    /**
     * 员工分页查询
     * @param employeePageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(EmployeePageQueryDTO employeePageQueryDTO) {
        //分页查询sql语句为:select * from employee limit 0,10;
        //借用pagehelper类来实现分页查询功能，利用pagehelper可以更好地存储分页参数page和pagesize并且实现sql语句的自动拼接
        PageHelper.startPage(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());

        Page<Employee> page = employeeMapper.pageQuery(employeePageQueryDTO);

        //获取参数用于封装PageResult
        long total = page.getTotal();
        List<Employee> records = page.getResult();

        return new PageResult(total, records);
    }

    /**
     * 启用或禁用员工
     * @param status
     * @param id
     */
    @Override
    public void startORstop(Integer status, Long id) {
        //为了让修改功能有更强的复用性，所以采用动态sql的形式在mapper中编写语句
        //因此要创建一个对象来适应可复用的动态update语句
//        Employee employee=new Employee();
//        employee.setId(id);
//        employee.setStatus(status);

        //另一种编程风格，这种风格的前提是该实体类中使用的@builder注解
        Employee employee = Employee.builder()
                .id(id)
                .status(status)
                .updateTime(LocalDateTime.now())
                .updateUser(BaseContext.getCurrentId())
                .build();

        employeeMapper.update(employee);
    }

    /**
     * 根据id查询员工
     * @param id
     * @return
     */
    @Override
    public Employee getById(Long id) {
        Employee employee=employeeMapper.selectById(id);
        //提高信息安全性，传递给前端的用户密码是四个*
        employee.setPassword("****");
        return employee;
    }

    /**
     * 修改员工信息
     * @param employeeDTO
     */
    @Override
    public void updateEmp(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        //复制属性
        BeanUtils.copyProperties(employeeDTO, employee);

        //扩充数据
        employee.setUpdateUser(BaseContext.getCurrentId());
        employee.setUpdateTime(LocalDateTime.now());

        //修改数据
        employeeMapper.update(employee);
    }
}
